/*
箭头语法以函数参数开头，然后是箭头=>，然后是函数体。
下面是箭头函数的以下不同变体。这些示例是用ES5语法和ES6箭头函数语法编写的
*/
const fruits = [
    {name: 'apple', price: 100}, 
    {name: 'orange', price: 80}, 
    {name: 'banana', price: 120}
];

//变体1
//当没有参数，必须要有一个空括号
var countFruitsArrow = () => fruits.length;
//对应的es5
var countFruitsEs5 = function () {
    return fruits.length;
}
//演示
console.log(countFruitsArrow());
console.log(countFruitsEs5());

console.log()
console.log('------------------')


//变体2
//当有一个参数，一个空括号可以省略
var filterfromArrow = fruits.filter(fruit => fruit.price > 100);
//对应的es5
var filterfromEs5 = fruits.filter(function(fruit) {
    return fruit.price > 100;
});
console.log(filterfromArrow);
console.log(filterfromEs5);

console.log()
console.log('------------------')

//变体3
//函数返回对象字面量(object literal) 需要用括号包起来
var inventoryArrow = fruits.map(fruit => ({name: fruit.name, storage: 1}));
//对应的es5
var inventoryEs5 = fruits.map(function(fruit) {
    return {name: fruit.name, storage: 1};
});

console.log(inventoryArrow);
console.log(inventoryEs5);

console.log()
console.log('------------------')

//变体4 
//当函数具有其他语句 并且有返回值 则必须有return语句
var inventoryArrow2 = fruits.map(fruit => {
    console.log('Checking ' + fruit.name + 'storage');
    return {name: fruit.name, storage: 1};
});
//对应的es5
var inventoryEs52 = fruits.map(function(fruit) {
    console.log('Checking ' + fruit.name + 'storage');
    return {name: fruit.name, storage: 1};
});

console.log(inventoryArrow2);
console.log(inventoryEs52);

console.log()
console.log('------------------')


//3的补充
//若箭头函数后面是{} 其内部是函数体 和正常函数一样
var sum = (a, b) => {return a + b;};
console.log(sum(2, 3));
//下面这种不会正常工作
var sum2 = (a, b) => { a + b;};
console.log(sum2(2, 3));  //undefined
//下面这种会正常工作
var sum3 = (a, b) =>  a + b;
console.log(sum3(1, 2));  //3
